<template>
  <!-- 上传组件 -->
  <el-upload
    v-model="imgUrl"
    class="avatar-uploader"
    :show-file-list="false"
    list-type="picture-card"
    :before-upload="handleBeforeUpload"
    :http-request="uploadFile"
  >
    <img v-if="imgUrl" :src="imgUrl" class="single-uploader__image" />
    <el-icon v-else class="avatar-uploader-icon">
    	<ele-Plus />
    </el-icon>
  </el-upload>
</template>

<script setup lang="ts">
import { ElMessage, UploadRawFile, UploadRequestOptions } from "element-plus";
import { addUploadTotem } from "/@/api/upload";
import { useVModel } from '@vueuse/core';

const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
});

const emit = defineEmits(["update:modelValue"]);
const imgUrl = useVModel(props, "modelValue", emit);

/**A
 * 自定义图片上传
 *
 * @param options
 */
async function uploadFile(options: UploadRequestOptions): Promise<any> {
  addUploadTotem(options).then(res=>{
  	imgUrl.value = res.data.src;
  })
}

/**
 * 限制用户上传文件的格式和大小
 */
function handleBeforeUpload(file: UploadRawFile) {
  if (file.size > 2 * 1048 * 1048) {
    ElMessage.warning("上传图片不能大于2M");
    return false;
  }
  return true;
}
</script>

<style scoped lang="scss">
	::v-deep .avatar-uploader .avatar {
	  width: 80px;
	  height: 80px;
	  display: block;
	}
	::v-deep .avatar-uploader .el-upload {
	  border: 1px dashed var(--el-border-color);
	  border-radius: 6px;
	  cursor: pointer;
	  position: relative;
	  overflow: hidden;
	  transition: var(--el-transition-duration-fast);
	}
	
	::v-deep .avatar-uploader .el-upload:hover {
	  border-color: var(--el-color-primary);
	}
	
	::v-deep .el-icon.avatar-uploader-icon {
	  font-size: 28px;
	  color: #8c939d;
	  width: 80px;
	  height: 80px;
	  text-align: center;
	}
</style>
